<template>
  <div class="diet-management-system">
    <!-- 顶部标题和选项卡 -->
    <div class="header">
      <h1>膳食管理系统</h1>
      <el-tabs v-model="activeTab" class="main-tabs">
        <el-tab-pane label="膳食分组" name="group"></el-tab-pane>
        <el-tab-pane label="膳食信息维护" name="diet"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 膳食分组模块 -->
      <div v-show="activeTab === 'group'" class="group-management">
        <div class="operation-bar">
          <el-button type="primary" @click="showAddGroupDialog">新增分组</el-button>
        </div>

        <el-table :data="groupList" border style="width: 100%">
          <el-table-column prop="code" label="分组编码" width="120" align="center"></el-table-column>
          <el-table-column prop="name" label="分组名称" align="center"></el-table-column>
          <el-table-column prop="status" label="启用状态" width="150" align="center">
            <template #default="{row}">
              <el-tag :type="row.status === 'enabled' ? 'success' : 'danger'" effect="dark">
                {{ row.status === 'enabled' ? '● 已启用' : '● 已禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center"></el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button size="small" @click="handleEditGroup(scope.row.id)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDeleteGroup(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
            :title="groupDialogTitle"
            v-model="groupDialogVisible"
            width="500px"
            :close-on-click-modal="false">
          <el-form
              :model="groupForm"
              :rules="groupRules"
              ref="groupFormRef"
              label-width="100px"
              label-position="top">
            <el-form-item label="分组编码" prop="code">
              <el-input v-model="groupForm.code" placeholder="请输入分组编码"></el-input>
            </el-form-item>
            <el-form-item label="分组名称" prop="name">
              <el-input v-model="groupForm.name" placeholder="请输入分组名称"></el-input>
            </el-form-item>
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="groupForm.status">
                <el-radio label="enabled">启用</el-radio>
                <el-radio label="disabled">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                  v-model="groupForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="groupDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitGroupForm">保存</el-button>
            </span>
          </template>
        </el-dialog>
      </div>

      <!-- 膳食信息维护模块 -->
      <div v-show="activeTab === 'diet'" class="diet-management">
        <div class="diet-header">
          <el-select
              v-model="currentGroupId"
              placeholder="请选择分组"
              style="width: 200px; margin-right: 15px;"
              @change="handleGroupChange"
          >
            <el-option
                v-for="group in enabledGroups"
                :key="group.id"
                :label="group.name"
                :value="group.id">
            </el-option>
          </el-select>

          <el-button type="primary" @click="showAddDietDialog">新增膳食</el-button>
          <el-input
              v-model="searchKeyword"
              placeholder="请输入..."
              style="width: 200px; margin-left: 15px;"
              clearable
              @clear="handleSearchClear"
              @keyup.enter="handleSearch">
          </el-input>
        </div>

        <!-- 显示当前分组名称 -->
        <div v-if="currentGroupName" style="margin: 10px 0; font-size: 14px;">
          当前分组：<el-tag>{{ currentGroupName }}</el-tag>
        </div>

        <el-table :data="filteredDietList" border style="width: 100%; margin-top: 10px;">
          <el-table-column label="图片" width="120" align="center">
            <template #default="{row}">
              <el-image
                  style="width: 80px; height: 80px"
                  :src="row.image"
                  fit="cover"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="膳食编码" width="120" align="center"></el-table-column>
          <el-table-column prop="name" label="膳食名称" align="center"></el-table-column>
          <el-table-column prop="price" label="价格" width="100" align="center">
            <template #default="{row}">
              {{ row.price?.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80" align="center"></el-table-column>
          <el-table-column prop="discount" label="折扣" width="100" align="center">
            <template #default="{row}">
              {{ row.discount === 1 ? '无' : (row.discount * 10)?.toFixed(1) + '折' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button size="small" @click="handleEditDiet(scope.row.id)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDeleteDiet(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="totalItems"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange">
          </el-pagination>
        </div>

        <!-- 新增/编辑膳食对话框 -->
        <el-dialog
            :title="dietDialogTitle"
            v-model="dietDialogVisible"
            width="700px"
            :close-on-click-modal="false">
          <el-form
              :model="dietForm"
              :rules="dietRules"
              ref="dietFormRef"
              label-width="100px"
              label-position="top">
            <div style="display: flex; justify-content: space-between;">
              <div style="width: 48%;">
                <el-form-item label="所属分组" prop="groupId" v-if="false">
                  <el-select
                      v-model="dietForm.groupId"
                      placeholder="请选择分组"
                      style="width: 100%"
                      disabled="disabled">
                    <el-option
                        v-for="group in enabledGroups"
                        :key="group.code"
                        :label="group.name"
                        :value="group.code">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="膳食编码" prop="code">
                  <el-input v-model="dietForm.code" placeholder="请输入膳食编码"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                  <el-input-number
                      v-model="dietForm.price"
                      :min="0"
                      :precision="2"
                      :step="0.1"
                      style="width: 100%"></el-input-number>
                </el-form-item>
                <el-form-item label="禁忌人群">
                  <el-input
                      v-model="dietForm.forbiddenPeople"
                      placeholder="请输入禁忌人群"></el-input>
                </el-form-item>
                <el-form-item label="启用状态" prop="status">
                  <el-radio-group v-model="dietForm.status">
                    <el-radio label="enabled">启用</el-radio>
                    <el-radio label="disabled">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="图片">
                  <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleImageSuccess"
                      :before-upload="beforeImageUpload">
                    <img v-if="dietForm.image" :src="dietForm.image" class="avatar">
                    <div v-else class="uploader-placeholder">
                      <el-icon><Plus /></el-icon>
                      <div class="uploader-text">点击上传</div>
                      <div class="uploader-hint">上传jpg/png，建议格式200*200</div>
                    </div>
                  </el-upload>
                </el-form-item>
              </div>
              <div style="width: 48%;">
                <el-form-item label="备注说明">
                  <el-input
                      v-model="dietForm.remark"
                      type="textarea"
                      :rows="5"
                      placeholder="请输入备注说明"></el-input>
                </el-form-item>
                <el-form-item label="膳食名称" prop="name">
                  <el-input v-model="dietForm.name" placeholder="请输入膳食名称"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                  <el-select v-model="dietForm.unit" placeholder="请选择" style="width: 100%">
                    <el-option label="份" value="份"></el-option>
                    <el-option label="个" value="个"></el-option>
                    <el-option label="只" value="只"></el-option>
                    <el-option label="碗" value="碗"></el-option>
                    <el-option label="盘" value="盘"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="口味">
                  <el-select v-model="dietForm.taste" placeholder="请选择" style="width: 100%">
                    <el-option label="酸辣" value="酸辣"></el-option>
                    <el-option label="麻辣" value="麻辣"></el-option>
                    <el-option label="清淡" value="清淡"></el-option>
                    <el-option label="甜" value="甜"></el-option>
                    <el-option label="咸鲜" value="咸鲜"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否推荐">
                  <el-checkbox v-model="dietForm.recommended">推荐</el-checkbox>
                </el-form-item>
                <el-form-item label="折扣">
                  <div style="display: flex; align-items: center;">
                    <el-input-number
                        v-model="dietForm.discount"
                        :min="0.1"
                        :max="1"
                        :step="0.1"
                        :precision="1"
                        style="width: 120px;"></el-input-number>
                    <span style="margin-left: 10px; color: #999;">{{ dietForm.discount === 1 ? '无折扣' : (dietForm.discount * 10).toFixed(1) + '折' }}</span>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dietDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitDietForm">保存</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, reactive, computed, onMounted, watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from "axios";
import qs from "qs";

export default {
  name: 'DietManagementSystem',
  components: { Plus },
  setup() {
    // 当前激活的选项卡
    const activeTab = ref('group')

    // 分组数据
    const groupList = ref([])
    const groupForm = ref({
      id: '',
      code: '',
      name: '',
      status: 'enabled',
      remark: ''
    })

    // 膳食数据
    const dietList = ref([])
    const currentGroupId = ref('')
    const currentGroupName = ref('')
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)

    // 加载分组数据
    const loadMealsGroup = () => {
      axios.get(BASE_URL + '/v1/mealsGroup/select?')
          .then((response) => {
            if (response.data.state == 2000) {
              groupList.value = response.data.data
            } else {
              ElMessage.error(response.data.msg)
            }
          })
    }

    // 按分组加载膳食数据
    const loadMealsByGroup = async (groupId) => {
      try {
        const response = await axios.get(`${BASE_URL}/v1/meals/select?groupId=${groupId}`)
        if(response.data.state === 2000) {
          dietList.value = response.data.data.map(item => ({
            ...item,
            price: parseFloat(item.price) || 0,
            discount: parseFloat(item.discount) || 1
          }))
          currentPage.value = 1 // 重置页码
        } else {
          ElMessage.error(response.data.msg || '加载膳食数据失败')
        }
      } catch (error) {
        console.error('加载膳食数据失败:', error)
        ElMessage.error('加载膳食数据失败，请检查网络')
      }
    }

    // 已启用的分组
    const enabledGroups = computed(() => {
      return groupList.value.filter(group => group.status === 'enabled')
    })

    // 设置默认选中第一个分组并加载数据
    watch(enabledGroups, (newVal) => {
      if (newVal.length > 0) {
        currentGroupId.value = newVal[0].id
        currentGroupName.value = newVal[0].name
        loadMealsByGroup(newVal[0].id)
      }
    }, {immediate: true})

    // 分组变更处理
    const handleGroupChange = (groupId) => {
      const selectedGroup = enabledGroups.value.find(g => g.id === groupId)
      if(selectedGroup) {
        currentGroupName.value = selectedGroup.name
        loadMealsByGroup(groupId)
      }
    }

    // 过滤后的膳食列表
    const filteredDietList = computed(() => {
      let list = dietList.value

      if(searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        list = list.filter(item =>
            (item.code && item.code.toLowerCase().includes(keyword)) ||
            (item.name && item.name.toLowerCase().includes(keyword))
        )
      }

      const start = (currentPage.value - 1) * pageSize.value
      const end = currentPage.value * pageSize.value
      return list.slice(start, end)
    })

    // 总条目数
    const totalItems = computed(() => {
      if(searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        return dietList.value.filter(item =>
            (item.code && item.code.toLowerCase().includes(keyword)) ||
            (item.name && item.name.toLowerCase().includes(keyword))
        ).length
      }
      return dietList.value.length
    })

    // 分组对话框相关
    const groupDialogVisible = ref(false)
    const groupDialogTitle = ref('新增分组')
    const groupFormRef = ref(null)
    const isGroupEditMode = ref(false)

    const groupRules = {
      code: [{ required: true, message: '请输入分组编码', trigger: 'blur' }],
      name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }

    // 膳食对话框相关
    const dietDialogVisible = ref(false)
    const dietDialogTitle = ref('新增膳食')
    const dietFormRef = ref(null)
    const isDietEditMode = ref(false)
    const currentEditDietId = ref(null)

    const dietForm = reactive({
      id: '',
      groupId: '',
      code: '',
      name: '',
      price: 0,
      unit: '份',
      discount: 1,
      image: '',
      status: 'enabled',
      forbiddenPeople: '',
      remark: '',
      taste: '',
      recommended: false
    })

    const dietRules = {
      groupId: [{ required: true, message: '请选择分组', trigger: 'change' }],
      code: [{ required: true, message: '请输入膳食编码', trigger: 'blur' }],
      name: [{ required: true, message: '请输入膳食名称', trigger: 'blur' }],
      price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
      unit: [{ required: true, message: '请选择单位', trigger: 'change' }]
    }

    // 分组操作
    const showAddGroupDialog = () => {
      groupDialogTitle.value = '新增分组'
      isGroupEditMode.value = false
      resetGroupForm()
      groupDialogVisible.value = true
    }

    const handleEditGroup = (id) => {
      groupDialogTitle.value = '编辑分组'
      isGroupEditMode.value = true
      groupDialogVisible.value = true
      axios.get(BASE_URL+'/v1/mealsGroup/select?id='+id).then((response)=>{
        if(response.data.state == 2000){
          groupForm.value = response.data.data[0]
        }else{
          ElMessage.error(response.data.msg)
        }
      })
    }

    const submitGroupForm = () => {
      let data = qs.stringify(groupForm.value)
      axios.post(BASE_URL+'/v1/mealsGroup/save?'+data)
          .then((response)=>{
            if(response.data.state===2000){
              groupDialogVisible.value = false
              groupForm.value = {}
              loadMealsGroup()
              ElMessage.success('保存成功')
            }else{
              ElMessage.error(response.data.msg)
            }
          })
    }

    const handleDeleteGroup = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除该分组吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 1. 先查询该分组下的膳食
        const mealsResponse = await axios.get(`${BASE_URL}/v1/meals/select?groupId=${id}`)

        if (mealsResponse.data.state !== 2000) {
          ElMessage.error(mealsResponse.data.msg || '查询分组下膳食失败')
          return
        }

        // 2. 检查是否有膳食数据
        const mealsData = mealsResponse.data.data || []

        if (mealsData.length > 0) {
          ElMessage.error(`该分组下有 ${mealsData.length} 个膳食，请先删除这些膳食`)
          return
        }

        // 3. 如果没有膳食，则删除分组
        const deleteResponse = await axios.post(`${BASE_URL}/v1/mealsGroup/delete/${id}`)

        if (deleteResponse.data.state === 2000) {
          ElMessage.success('删除分组成功!')
          loadMealsGroup()
        } else {
          ElMessage.error(deleteResponse.data.msg || '删除分组失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分组出错:', error)
          ElMessage.error('删除分组过程中出错')
        }
      }
    }

    const handleDeleteDiet = (id) => {
      ElMessageBox.confirm('确定要删除该膳食吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post(BASE_URL+'/v1/meals/delete/'+id)
            .then((response)=>{
              if(response.data.state===2000){
                loadMealsByGroup(currentGroupId.value)
                ElMessage.success('删除成功')
              }else{
                ElMessage.error(response.data.msg)
              }
            })
      }).catch(() => {})
    }

    const resetGroupForm = () => {
      groupFormRef.value?.resetFields()
      groupForm.value = {
        id: '',
        code: '',
        name: '',
        status: 'enabled',
        remark: ''
      }
    }

    // 膳食操作
    const showAddDietDialog = () => {
      dietDialogTitle.value = '新增膳食'
      isDietEditMode.value = false
      resetDietForm()
      dietForm.groupId = currentGroupId.value
      dietDialogVisible.value = true
    }

    const handleEditDiet = (id) => {
      dietDialogTitle.value = '编辑膳食'
      isDietEditMode.value = true
      currentEditDietId.value = id
      dietDialogVisible.value = true

      axios.get(BASE_URL+'/v1/meals/select?id='+id)
          .then((response) => {
            if(response.data.state === 2000 && response.data.data.length > 0) {
              const dietData = response.data.data[0]
              Object.assign(dietForm, {
                id: dietData.id,
                groupId: dietData.groupId,
                code: dietData.code,
                name: dietData.name,
                price: parseFloat(dietData.price) || 0,
                unit: dietData.unit || '份',
                discount: parseFloat(dietData.discount) || 1,
                image: dietData.image || '',
                status: dietData.status || 'enabled',
                forbiddenPeople: dietData.forbiddenPeople || '',
                remark: dietData.remark || '',
                taste: dietData.taste || '',
                recommended: dietData.recommended || false
              })
            } else {
              ElMessage.error(response.data.msg || '获取膳食数据失败')
            }
          })
          .catch(error => {
            console.error('获取膳食数据失败:', error)
            ElMessage.error('获取膳食数据失败')
          })
    }

    const submitDietForm = () => {
      dietFormRef.value?.validate((valid) => {
        if (valid) {
          const formData = {
            id: dietForm.id,
            groupId: dietForm.groupId,
            code: dietForm.code,
            name: dietForm.name,
            price: dietForm.price,
            unit: dietForm.unit,
            discount: dietForm.discount,
            image: dietForm.image,
            status: dietForm.status,
            forbiddenPeople: dietForm.forbiddenPeople,
            remark: dietForm.remark,
            taste: dietForm.taste,
            recommended: dietForm.recommended
          }

          const data = qs.stringify(formData)

          axios.post(BASE_URL+'/v1/meals/save?'+data)
              .then((response) => {
                if(response.data.state === 2000) {
                  dietDialogVisible.value = false
                  loadMealsByGroup(currentGroupId.value)
                  ElMessage.success('保存成功')
                } else {
                  ElMessage.error(response.data.msg || '保存失败')
                }
              })
              .catch(error => {
                console.error('保存膳食失败:', error)
                ElMessage.error('保存膳食失败')
              })
        } else {
          return false
        }
      })
    }

    const resetDietForm = () => {
      dietFormRef.value?.resetFields()
      currentEditDietId.value = null
      Object.assign(dietForm, {
        id: '',
        groupId: currentGroupId.value,
        code: '',
        name: '',
        price: 0,
        unit: '份',
        discount: 1,
        image: '',
        status: 'enabled',
        forbiddenPeople: '',
        remark: '',
        taste: '',
        recommended: false
      })
    }

    // 图片上传
    const handleImageSuccess = (response, file) => {
      dietForm.image = URL.createObjectURL(file.raw)
    }

    const beforeImageUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    }

    // 搜索和分页
    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleSearchClear = () => {
      searchKeyword.value = ''
      currentPage.value = 1
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handlePageChange = (val) => {
      currentPage.value = val
    }

    // 初始化加载数据
    onMounted(() => {
      loadMealsGroup()
    })

    return {
      activeTab,
      groupList,
      enabledGroups,
      currentGroupId,
      currentGroupName,
      dietList,
      filteredDietList,
      searchKeyword,
      currentPage,
      pageSize,
      totalItems,
      groupDialogVisible,
      groupDialogTitle,
      groupForm,
      groupRules,
      groupFormRef,
      showAddGroupDialog,
      handleEditGroup,
      handleDeleteGroup,
      submitGroupForm,
      dietDialogVisible,
      dietDialogTitle,
      dietForm,
      dietRules,
      dietFormRef,
      isDietEditMode,
      showAddDietDialog,
      handleEditDiet,
      handleDeleteDiet,
      submitDietForm,
      handleImageSuccess,
      beforeImageUpload,
      handleSearch,
      handleSearchClear,
      handleSizeChange,
      handlePageChange,
      handleGroupChange
    }
  }
}
</script>

<style scoped>
.diet-management-system {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.header h1 {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.main-tabs {
  margin-top: 15px;
}

.main-content {
  margin-top: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  text-align: right;
}

.diet-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.uploader-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
}

.uploader-placeholder .el-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.uploader-text {
  font-size: 14px;
  margin-bottom: 4px;
}

.uploader-hint {
  font-size: 12px;
  color: #999;
}
</style>